﻿using Abp;
using Abp.Application.Services;
using FwProject.Manager;
using FwProject.ShopApplication;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Abp.ObjectMapping;
using FwProject.ShoppingMall.EventAdvertising;
using Abp.Domain.Repositories;
using X.PagedList;
using System.Linq;
using AutoMapper.QueryableExtensions;
using FwProject.Authorization.Users;
using Abp.Authorization;

namespace FwProject.EventAdvertising.Dto
{
    /// <summary>
    /// 会员优惠券管理
    /// </summary>
    [AbpAuthorize]
    public class ShopUserCouponAppService : FwProjectAppServiceBase, IShopUserCouponAppService
    {
        private readonly ShopUserCouponManager _shopUserCouponManager;
        private readonly IRepository<ShopUserCoupon, Guid> _shopUserCouponRepository;
        private readonly IRepository<User, long> _userRepository;
        private Abp.IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="shopUserCouponManager"></param>
        /// <param name="shopUserCouponRepository"></param>
        /// <param name="userRepository"></param>
        public ShopUserCouponAppService(ShopUserCouponManager shopUserCouponManager, IRepository<ShopUserCoupon, Guid> shopUserCouponRepository, IRepository<User, long> userRepository)
        {

            _shopUserCouponManager = shopUserCouponManager;
            _guid = SequentialGuidGenerator.Instance;
            _map = NullObjectMapper.Instance;
            _shopUserCouponRepository = shopUserCouponRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 创建一个优惠券
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Guid> CreateShopUserCoupon(ShopUserCouponInput Input)
        {
            var model = _map.Map<ShopUserCoupon>(Input);
            model.Id = _guid.Create();
            return await _shopUserCouponManager.CreateShopUserCoupon(model);
        }
        /// <summary>
        /// 修改一个优惠券
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task EditShopUserCoupon(Guid Id, ShopUserCouponInput Input)
        {
            var model = _shopUserCouponRepository.Get(Id);
            model = _map.Map(Input, model);
            await _shopUserCouponManager.UpdateShopUserCoupon(model);
        }
        /// <summary>
        /// 删除一个优惠券
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task CleanRemoveShopUserCoupon(Guid Id)
        {
            var model = _shopUserCouponRepository.Get(Id);
            await _shopUserCouponManager.DeleteShopUserCoupon(model);
        }

        /// <summary>
        /// 批量删除优惠券一个优惠券
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task CleanRemoveListShopUserCoupon(List<Guid> Input)
        {
            foreach (var item in Input)
            {
                var model = _shopUserCouponRepository.Get(item);
                await _shopUserCouponManager.DeleteShopUserCoupon(model);
            }

        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pageSize">条数</param>
        /// <param name="useStatus">使用状态</param>
        /// <param name="CouponTitile">优惠券标题</param>
        /// <param name="beginTime">优惠开始使用时间</param>
        /// <param name="endTime">优惠券结束使用时间</param>
        /// <param name="coupontype">优惠券使用类别</param>
        /// <param name="usecoupon">使用范围</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<IPagedList<ShopUserCouponDto>> GetSelfCouponPageList(int page, int pageSize, UseStatus? useStatus, string CouponTitile, DateTime? beginTime, DateTime? endTime, CouponType? coupontype, UseCoupon? usecoupon, int overdue = 0)
        {

            var list = _shopUserCouponRepository.GetAllIncluding(o => o.ShopCoupon).Where(O => O.UserId == AbpSession.UserId.Value && O.UseStatus != UseStatus.Delete);

            if (beginTime != null)
                list = list.Where(o => o.ShopCoupon.UseBeginTime >= beginTime);

            if (endTime != null)
                list = list.Where(o => o.ShopCoupon.UseEndTime <= endTime.Value.AddHours(24));

            if (coupontype != null)
                list = list.Where(o => o.ShopCoupon.CouponType == coupontype);

            if (usecoupon != null)
                list = list.Where(o => o.ShopCoupon.UseCoupon == usecoupon);

            ///优惠券使用状态
            if (useStatus != null)
                list = list.Where(o => o.UseStatus == useStatus);
            if (overdue == 1)
                list = list.Where(o => o.UseStatus == UseStatus.Unused && o.ShopCoupon.UseEndTime < DateTime.Now);

            return await list.OrderByDescending(o => o.CreationTime).ProjectTo<ShopUserCouponDto>().ToPagedListAsync(page, pageSize);
        }
        /// <summary>
        /// app购买商品时根据订单信息获取可用优惠券
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pageSize">条数</param>
        /// <param name="Producttypeguid">商品类别组</param>
        /// <returns></returns>
        [AbpAuthorize]

        public async Task<IPagedList<ShopUserCouponDto>> GetSelfAvailableCouponPageList(int page, int pageSize, List<OrderShopUserCoupon> Producttypeguid)
        {

            var list = _shopUserCouponRepository.GetAllIncluding(o => o.ShopCoupon).Where(O => O.UserId == AbpSession.UserId.Value && O.UseStatus == UseStatus.Unused);
            list = list.Where(o => o.ShopCoupon.UseBeginTime <= DateTime.Now && o.ShopCoupon.UseEndTime >= DateTime.Now);

            if (Producttypeguid.Count > 0)
                list = list.Where(o => (o.ShopCoupon.CouponType == CouponType.All && o.ShopCoupon.UseCoupon == UseCoupon.Universal)
                || (o.ShopCoupon.CouponType == CouponType.Single && o.ShopCoupon.UseCoupon == UseCoupon.Universal && Producttypeguid.Any(s => s.ShopTypeId == o.ShopCoupon.ProductTypeId))
                || (o.ShopCoupon.CouponType == CouponType.All && o.ShopCoupon.UseCoupon == UseCoupon.FullReduction && Producttypeguid.Any(s => s.Total >= o.ShopCoupon.UsePrice))
                || (o.ShopCoupon.CouponType == CouponType.Single && o.ShopCoupon.UseCoupon == UseCoupon.FullReduction && Producttypeguid.Any(s => s.Total >= o.ShopCoupon.UsePrice && s.ShopTypeId == o.ShopCoupon.ProductTypeId))
                || (o.ShopCoupon.CouponType == CouponType.All && o.ShopCoupon.UseCoupon == UseCoupon.FullReduction && o.ShopCoupon.UsePrice<= Producttypeguid.Sum(s=>s.Total))

                );
            return await list.OrderByDescending(o => o.CreationTime).ProjectTo<ShopUserCouponDto>().ToPagedListAsync(page, pageSize);
        }


        #region 后台管理
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="couponid"></param>
        /// <returns></returns>

        public async Task<LayerDataBaseDto> GetUserCouponLayerDataAsync(int page, int limit, Guid couponid)
        {
            var query = _shopUserCouponRepository.GetAllIncluding(o=>o.ShopCoupon).Where(o => o.ShopCouponId == couponid);

            var pagelist = await query.OrderByDescending(o => o.CreationTime).ProjectTo<ShopUserCouponDto>().ToPagedListAsync(page, limit);

            foreach (var item in pagelist)//跨数据库无法联合查询
            {
                item.UserName = (await _userRepository.GetAsync(item.UserId)).UserName;
            }

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }

        /// <summary>
        /// 获取餐厅用户类型
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<LayerDataBaseDto> GetMemberLayerDataAsync(int page, int limit, string keyword)
        {
            var query = _userRepository.GetAll().Where(o => o.EmployeeType == EmployeeType.餐厅老板类型);

            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(o => o.UserName.Contains(keyword) || o.Name.Contains(keyword));

            var pagelist = await query.OrderBy(o => o.Id).Select(o => new { o.Id, o.Name, o.UserName }).ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }
        /// <summary>
        /// 发放优惠券
        /// </summary>
        /// <param name="CouponId"></param>
        /// <param name="Members"></param>
        /// <returns></returns>
        public async Task BatchSaveShopUserCouponAsync(Guid CouponId, string Members)
        {
            if (!string.IsNullOrEmpty(Members))
            {
                var memberids = Members.Split(',');

                foreach (var item in memberids)
                {
                    ShopUserCoupon entity = new ShopUserCoupon
                    {
                        Id = _guid.Create(),
                        ShopCouponId = CouponId,
                        UserId = long.Parse(item),
                        UseStatus = UseStatus.Unused
                    };

                    await _shopUserCouponManager.CreateShopUserCoupon(entity);
                }
            }
        }
        #endregion
    }
}
